#include <config.h>
#include <core.h>


int filesize(char *filename)
{
   int fd = open(filename,O_RDONLY); 
   if(fd < 0){
      ERROR("cant open %s:",filename);
      return fd;
   }
   int len = lseek(fd,0,SEEK_END);
   lseek(fd,0,SEEK_CUR);
   close(fd);
   return len;
}

int readfile(char *filename,char **buff)
{
   int fd = open(filename,O_RDONLY); 
   if(fd < 0){
      ERROR("cant open %s:",filename);
      return fd;
   }

   int len = lseek(fd,0,SEEK_END);   
   lseek(fd,0,SEEK_SET);
   *buff = (char*)malloc(len+1);
   memset(*buff,0,len+1);

   return readfile_by_fd(fd,buff,len);
}

int readfile_by_fd(int fd,char **buff,int len)
{
   int cnt=-1,total=0;
   while((total < len) && (cnt=read(fd,*buff+total,len-total)) >0){
     total += cnt; 
   }

   close(fd);
   return total;
}


int readfile_by_pool(char *filename,char **buff,pool_t *pool)
{
   int fd = open(filename,O_RDONLY); 
   if(fd < 0){
      ERROR("cant open %s:",filename);
      return fd;
   }

   int len = lseek(fd,0,SEEK_END);   
   lseek(fd,0,SEEK_SET);
   *buff  = pool_calloc(pool,len+1); 

   return readfile_by_fd(fd,buff,len);
}  

int writetoFile(char *fileName,char *buff,int len)
{
   INFO("%s  %s %d",fileName,buff,len);
   return 0; 
}
